package com.ruoyi.framework.config;

import com.alibaba.druid.pool.xa.DruidXADataSource;
import com.alibaba.druid.spring.boot.autoconfigure.properties.DruidStatProperties;
import com.alibaba.druid.util.Utils;
import com.atomikos.jdbc.AtomikosDataSourceBean;
import com.ruoyi.common.enums.DataSourceType;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.framework.config.properties.DruidProperties;
import com.ruoyi.framework.datasource.DynamicDataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;

import javax.servlet.*;
import javax.sql.DataSource;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * druid 配置多数据源
 *
 * @author ruoyi
 */
@Configuration
@Slf4j
public class DruidConfig {
    public static DataSource getXaDataSource(DruidXADataSource druidXADataSource, String sourceKey) {
        AtomikosDataSourceBean sourceBean = new AtomikosDataSourceBean();
        sourceBean.setXaDataSource(druidXADataSource);
        // 必须为数据源指定唯一标识
        sourceBean.setMinPoolSize(5);
        sourceBean.setMaxPoolSize(20);
        sourceBean.setBorrowConnectionTimeout(60);
        sourceBean.setTestQuery("SELECT 1 FROM DUAL");
        sourceBean.setUniqueResourceName(sourceKey);
        return sourceBean;
    }

    @Bean(name = "masterDataSource")
    @ConfigurationProperties("spring.datasource.druid.master")
    public DataSource masterDataSource(Environment env, DruidProperties druidProperties) {
        DruidXADataSource druidXADataSource=build(env,"spring.datasource.druid.master.");
        druidXADataSource = druidProperties.dataSource(druidXADataSource);
        return getXaDataSource(druidXADataSource, DataSourceType.MASTER.name());
    }

    @Bean(name = "slaveDataSource")
    @ConfigurationProperties("spring.datasource.druid.slave")
    @ConditionalOnProperty(prefix = "spring.datasource.druid.slave", name = "enabled", havingValue = "true")
    public DataSource slaveDataSource(Environment env, DruidProperties druidProperties) {
        DruidXADataSource druidXADataSource=build(env,"spring.datasource.druid.slave.");
        druidXADataSource = druidProperties.dataSource(druidXADataSource);
        return getXaDataSource(druidXADataSource, DataSourceType.SLAVE.name());
    }

    /**
     * @ConfigurationProperties貌似不支持多层嵌套的类的属性注入
     * @param env
     * @param prefix
     * @return
     */
    protected DruidXADataSource build(Environment env, String prefix)
    {
        DruidXADataSource druidXADataSource = new DruidXADataSource();
        druidXADataSource.setUrl(env.getProperty(prefix + "url"));
        druidXADataSource.setUsername(env.getProperty(prefix + "username"));
        druidXADataSource.setPassword(env.getProperty(prefix + "password"));
        return druidXADataSource;
    }

    //目前来看只在spring boot热部署那块用了
    @Bean(name = "dynamicDataSource")
    @Primary
    public DynamicDataSource dataSource(DataSource masterDataSource) {
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put(DataSourceType.MASTER.name(), masterDataSource);
        //载yml中配置多数据源需要手动判断是否生效并添加到spring的动态数据源中
        if (SpringUtils.containsBean("slaveDataSource"))
            setDataSource(targetDataSources, DataSourceType.SLAVE.name(), "slaveDataSource");
        return new DynamicDataSource(masterDataSource, targetDataSources);
    }

    /**
     * 设置数据源
     *
     * @param targetDataSources 备选数据源集合
     * @param sourceName        数据源名称
     * @param beanName          bean名称
     */
    public void setDataSource(Map<Object, Object> targetDataSources, String sourceName, String beanName) {
        try {
            DataSource dataSource = SpringUtils.getBean(beanName);
            targetDataSources.put(sourceName, dataSource);
        } catch (Exception e) {
            log.error("bean工厂获取{}出错：{}",beanName,e.getMessage());
        }
    }

    /**
     * 去除监控页面底部的广告
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    @Bean
    @ConditionalOnProperty(name = "spring.datasource.druid.statViewServlet.enabled", havingValue = "true")
    public FilterRegistrationBean removeDruidFilterRegistrationBean(DruidStatProperties properties) {
        // 获取web监控页面的参数
        DruidStatProperties.StatViewServlet config = properties.getStatViewServlet();
        // 提取common.js的配置路径
        String pattern = config.getUrlPattern() != null ? config.getUrlPattern() : "/druid/*";
        String commonJsPattern = pattern.replaceAll("\\*", "js/common.js");
        final String filePath = "support/http/resources/js/common.js";
        // 创建filter进行过滤
        Filter filter = new Filter() {
            @Override
            public void init(javax.servlet.FilterConfig filterConfig) throws ServletException {
            }

            @Override
            public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
                    throws IOException, ServletException {
                chain.doFilter(request, response);
                // 重置缓冲区，响应头不会被重置
                response.resetBuffer();
                // 获取common.js
                String text = Utils.readFromResource(filePath);
                // 正则替换banner, 除去底部的广告信息
                text = text.replaceAll("<a.*?banner\"></a><br/>", "");
                text = text.replaceAll("powered.*?shrek.wang</a>", "");
                response.getWriter().write(text);
            }

            @Override
            public void destroy() {
            }
        };
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        registrationBean.setFilter(filter);
        registrationBean.addUrlPatterns(commonJsPattern);
        return registrationBean;
    }
}
